#!/usr/bin/python
# -*- coding: UTF-8 -*-

import os
import sys
import subprocess
import time
from colorama import Fore, Back, Style,init
init(autoreset=True)


# print ("Number of arguments:", len(sys.argv), "arguments")
# print ("Argument List:", str(sys.argv))

typ="work"
if len(sys.argv)>=2:
    typ=sys.argv[1]

print(Fore.YELLOW+"typ={0}".format(typ))

ROOT=os.path.abspath(os.path.dirname(__file__))
print(Fore.YELLOW+"当前目录为:{0}".format(ROOT))
PROJ_ROOT=os.path.abspath(os.path.dirname(ROOT))
print(Fore.YELLOW+"当前项目目录为:{0}".format(PROJ_ROOT))

SERVICE_ROOT=os.path.join(PROJ_ROOT,"service")
print(Fore.YELLOW+"当前服务目录为:{0}".format(SERVICE_ROOT))
print(Style.RESET_ALL)
api_cmd_lines=[]
rpc_cmd_lines=[]
other_cmd_lines=[]

except_service=[
    # {"typ":"rpc","service":"sms"},
    # {"typ":"api","service":"leaderboard"},
]

def isInvalid(typ,service):
    for s in except_service:
        if s['typ'] == typ and s['service'] == service:
            return True
    pass

for root, dirs, files in os.walk(SERVICE_ROOT, topdown=False):
    for name in dirs:
        cur_service=os.path.join(root, name)
        makefile=os.path.join(cur_service,"Makefile")
        if os.path.exists(makefile):
            cmd=None
            if typ=="home":
                cmd="make run-home"
                pass
            else:
                cmd="make run"
                pass

            cmdline="cd %s && %s "%(cur_service,cmd)
            # print("cmdline: %s" %cmdline)
            service=os.path.basename(os.path.dirname(cur_service))
            if name=='rpc':
                rpc_cmd_lines.append({"cmd":cmdline,"service":service,"typ":"rpc"})
                pass
            elif name=='api':
                api_cmd_lines.append({"cmd":cmdline,"service":service,"typ":"api"})
                pass
            else:
                other_cmd_lines.append({"cmd":cmdline,"service":service,"typ":name})
                pass
            pass
    pass

# print(rpc_cmd_lines)
sleep_procs = []

cmdlines=rpc_cmd_lines+other_cmd_lines+api_cmd_lines

first_api=True
for cmdline in cmdlines:
    cmd=cmdline['cmd']
    typ=cmdline['typ']
    service=cmdline['service']

    invalid=isInvalid(typ,service)
    if invalid:
        continue

    # print(Fore.YELLOW+"cmdline: %s" % cmd)
    proc = subprocess.Popen(cmd,
                        stdin=subprocess.PIPE,
                        stdout=subprocess.PIPE,
                        shell=True)
    sleep_procs.append(proc)

    if first_api and type == 'api':
        print(Fore.RED+"开始启动第一次启动API等待10秒")
        print(Style.RESET_ALL)
        time.sleep(10)
        pass

    print(Fore.GREEN+"开始启动{0},{1}".format(typ,service))
    print(Style.RESET_ALL)
    if typ=='api' or typ=='rpc':
        for line in iter(proc.stdout.readline,''):
            s=line.rstrip().decode("utf-8")
            index=s.find("server at")
            if index != -1:
                print(Fore.RED+"启动{0},{1}完毕".format(typ,service))
                print(Style.RESET_ALL)
                time.sleep(1)
                break
                pass
    else:
        time.sleep(2)
        pass

    pass

for proc in sleep_procs:
    proc.communicate()
